#include <iostream>
#include <vector>
#include <queue>

using namespace std;

/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if (!root) return ret;
        queue<TreeNode*> q; q.push(root);
        bool reverse = false;
        while (!q.empty()) {
            int currentSize = q.size();
            vector<int> level(currentSize);
            for (int i=0; i<currentSize; ++i) {
                auto node = q.front(); q.pop();
                int pos = reverse ? currentSize - i - 1 : i;
                level[pos] = node->val;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            ret.push_back(level);
            reverse = !reverse;
        }
        return ret;
    }
};
